import React from 'react';
import {WeaNewScroll, WeaErrorPage, WeaTools, WeaLocaleProvider} from 'ecCom';
const getLabel = WeaLocaleProvider.getLabel;
import { Spin } from 'antd';
import { isEqual, isEmpty } from 'lodash';
import { openLinkUrl } from '../../util/common';
import Signature from './Signature';
import './signview.css';
import { inject, observer } from 'mobx-react';
@inject('wfForwardStore')
@observer
class SignView extends React.Component{
	constructor(props) {
        super(props);
        this.state = {
            data: null,
            isMore: false,
            title: '',
            linkurl: '',
            requestid: '-1',
            signRequired:false,
            formRequired:false,
            rightMenus:[],
        }
        this.signviewPoistion = this.signviewPoistion.bind(this);
        this.getMoreSignData = this.getMoreSignData.bind(this);
        this.handleOnShow = this.handleOnShow.bind(this);
    }
    handleOnShow(){
    	const { signRequired, formRequired, linkurl } = this.state;
    	if(formRequired){
			openLinkUrl(linkurl,'2')
		}else{
			this.refs.Signature.onShow(signRequired);
		}
    }
    signviewPoistion(eid){
    	let that = this;
		var _contentDiv = jQuery("#signPreview_" + eid).find(".signContent");
		jQuery("#tabcontant_" + eid).find(".reqdetail").parent().hover(function() {
		    $(this).find(".imgdetail").show();
		},
		function() {
		    $(this).find(".imgdetail").hide();
		});
		jQuery("#tabcontant_" + eid).find(".imgdetail").bind("click",function() {
			var $this = jQuery(this).parents("tr:first").find(".reqdetail");
			var adom = jQuery(this).parents("tr:first").find("a");
		    _contentDiv.css("height", "332px");
		    $(".signPreview").hide();
		    var requestid = $(adom).attr("data-requestid");
		    var link = $(adom).attr("data-link");
	        var title = $(adom).attr("title");
		    WeaTools.callApi('/api/portal/workflowsign/signinfo', 'POST', {
		   		requestid
		   	}).then((data) => {
		        let showbtns = false;
		        let menus = [];
		        const rightMenus = data.rightmenuInfo.rightMenus || [];
			   	for (var i = 0; i < rightMenus.length; i++) {
			  		if(rightMenus[i].type == 'BTN_SUBBACKNAME' || rightMenus[i].type == 'BTN_SUBNOBACKNAME' || rightMenus[i].type == 'BTN_FORWARD'){
			  			menus.push(rightMenus[i]);
			  			showbtns = true;
		   			}
			   	}
			   	that.setState({
					signRequired: data.requiredInfo.required,
		            formRequired: data.requiredInfo.required,
		            rightMenus: menus
		        });
			   	var signPreview = jQuery("#signPreview_" + eid);
			    signPreview.find(".signMore").hide();
			    signPreview.height(showbtns ? 412:372);
		        that.setState({
		            title: title,
		            linkurl: link,
		            requestid,
		        });
			    let pagesize = 3;
			    let curPage = 1;
			    let totalCount = 0;
			   	WeaTools.callApi('/api/workflow/reqform/requestLog', 'POST', {
			   		requestid,
			   		maxrequestlogid:'',
			   		loadmethod: 'portal',
			   		firstload: true,
			   		requestLogParams: null,
			   		wfsignlddtcnt: pagesize,
			   		pgnumber: curPage,
			   	}).then((data) => {
			   		that.setState({
			            data: data.log_loglist,
			            isMore: false,
			        });
		            totalCount = parseInt(data.totalCount);
			        var etop = $this.parents(".item:first").offset().top;
			        var eleft = $this.parents(".item:first").offset().left;
			        //alert(eleft)
			        if ($this.parents(".item:first").css("position") == "static") {
			            etop = 0;
			            eleft = 0;
			        }
			        var left = $this.offset().left;
			        left = left - eleft;
			        var top = $this.offset().top;
			        var rtop = top - etop;
			        if (top < signPreview.height() || top - $(document).scrollTop() + 350 < $(window).height()) {
			            $(".arrowsblockup").hide();
			            $(".arrowsblock").show();
			            $(".signContainer").removeClass("signContainerup");
			            $(".signMore").removeClass("signMoreup");
			        } else {
			            $(".arrowsblockup").show();
			            $(".arrowsblock").hide();
			            $(".signContainer").addClass("signContainerup");
			            $(".signMore").addClass("signMoreup");
			            rtop = rtop - 332 - 20;
			            if ((curPage*3) < totalCount) {
			                rtop = rtop - 60;
			            } else {
			                rtop = rtop - 20;
			            }
			            rtop = rtop + 8 - 40;
			        }
			        //alert(top+rtop-$(document).scrollTop())
			        if (top + rtop - $(document).scrollTop() < 0) {
			            rtop = top - etop;
			            $(".arrowsblockup").hide();
			            $(".arrowsblock").show();
			            $(".signContainer").removeClass("signContainerup");
			            $(".signMore").removeClass("signMoreup");
			        }
			        rtop = rtop + 31;
			        signPreview.css("top", rtop);
			        signPreview.css("left", left);
			        signPreview.attr("top", rtop);
			        var ulheight = _contentDiv.find(".content").height();
			        if (ulheight > 332) {
			            ulheight = 332;
			            _contentDiv.height(ulheight);
			        }
			        _contentDiv.perfectScrollbar();
			        if ((curPage*3) >= totalCount) {
			            signPreview.find(".signMore").hide();
			            signPreview.find(".signMore").prev().css("border-bottom-width", "1px");
			        } else {
			            signPreview.find(".signMore").show();
			            const signHeight = signPreview.height();
			            signPreview.height(showbtns ? 412:372);
			            var paramsDom = signPreview.find(".params");
			            $(paramsDom).find("input[name='pageno']").val("1");
			            $(paramsDom).find("input[name='requestid']").val(requestid);
			            $(paramsDom).find("input[name='maxrequestlogid']").val(data.maxrequestlogid);
			            $(paramsDom).find("input[name='requestLogParams']").val(JSON.stringify(data.requestLogParams));
			            signPreview.find(".signMore").prev().css("border-bottom-width", "0px");
			        }
			        signPreview.show();
			    });
		    });
		})
		jQuery("#signPreview_" + eid).find(".signIconClose").bind("click",function() {
		    jQuery("#signPreview_" + eid).hide();
		})
	}
	getMoreSignData(eid){
		this.setState({
		     isMore: true,
		});
		var signPreview = jQuery("#signPreview_" + eid);
		var paramsDom = signPreview.find(".params");
      	var curPage = $(paramsDom).find("input[name='pageno']").val();
      	var requestid = $(paramsDom).find("input[name='requestid']").val();
        var maxrequestlogid = $(paramsDom).find("input[name='maxrequestlogid']").val();
       	var requestLogParams = $(paramsDom).find("input[name='requestLogParams']").val();	
		var nextPage = parseInt(curPage)+1;
		var pagesize = 3;
	   	WeaTools.callApi('/api/workflow/reqform/requestLog', 'POST', {
		   		requestid,
		   		maxrequestlogid,
		   		loadmethod: 'portal',
		   		firstload: false,
		   		requestLogParams,
		   		wfsignlddtcnt: pagesize,
		   		pgnumber: nextPage,
		   	}).then((data) => {
	   		if(!data.api_status){
				var odata = this.state.data;
		   		var newList = odata.concat(data.log_loglist);
		   		this.setState({
		            data: newList,
		            isMore: false,
			    });
			    if(data.log_loglist.length){
			    	$(`#signPreview_${eid} .scroller`).animate({scrollTop: 332 * (nextPage - 2) + data.log_loglist.length * 111} + 40, 1000); 
			    }
	            $(paramsDom).find("input[name='pageno']").val(nextPage);
	            $(paramsDom).find("input[name='requestid']").val(requestid);
	            $(paramsDom).find("input[name='maxrequestlogid']").val(data.maxrequestlogid);
	            $(paramsDom).find("input[name='requestLogParams']").val(requestLogParams);
		   		if(nextPage*3>parseInt(data.totalCount)){
		   			 signPreview.height(showbtns ? 410:370);
		   			 signPreview.find(".signMore").html(getLabel(126120,"没有更多数据"));
		   		}
	   		}else{
	   			window.console ? console.error(" errormsg : ",data.api_errormsg) : alert(" errormsg : ",data.api_errormsg);
	   		}
	   	});
	}
	componentDidMount(){
		this.signviewPoistion(this.props.eid);
	}
	componentDidUpdate(preProps){
		const { eid, tabid, refresh } = this.props;
		if(preProps.tabid !== tabid || refresh !== preProps.refresh){
			$("#signPreview_"+eid).css("display","none");
			this.signviewPoistion(eid);
		}
	}
	shouldComponentUpdate(nextProps, nextState){
        return !isEqual(nextProps, this.props) || !isEqual(nextState, this.state)
    }
	render(){
		const { eid, tabid, wfForwardStore } = this.props;
		const { data, isMore, linkurl, title, requestid, rightMenus } = this.state;
		const sdata = data || [];
		let html = null;
		if(sdata.length > 0){
			html = sdata.map((item,i)=>{
      			return <SignContent item={item}/>
  			});
		}else{
			html = <div className="sign-nosigndiv" id="nosigndiv">
				<img src="/images/ecology8/workflow/noSignNotice_wev8.png"/>&nbsp;
				<span>{getLabel(22521,"没有可以显示的数据")}</span>
			</div>
		}
		let ahtml = <div className="signContent">
			<div className="content">
				{html}
			</div>
			<div className="signMore" onClick={this.getMoreSignData.bind(this,eid)}>{getLabel(82720,"加载更多")}</div>
		</div>
		ahtml = <WeaNewScroll scrollId="element_signPreview_scroll" height={332}>{ahtml}</WeaNewScroll>
		if(!data || isMore){
			ahtml = <Spin>{ahtml}</Spin>
		}

		let btnsHtml = null;
		let showbtns = rightMenus && rightMenus.length;
		if(showbtns){
			let btnsArr = [];
			rightMenus.map(menu=>{
				if(menu.type == 'BTN_SUBBACKNAME' || menu.type == 'BTN_SUBNOBACKNAME'){
					btnsArr.push(<span className="signSubmitBtn"><a href="javascript:void(0);" onClick={this.handleOnShow}>{menu.menuName}</a></span>);
				}
				if(menu.type == 'BTN_FORWARD'){
					btnsArr.push(<span className="signSubmitForward"><a href="javascript:void(0);" onClick={() => wfForwardStore.setShowForward(true,requestid)}>{getLabel(6011,"转发")}</a></span>);
				}
			});
			btnsArr.push(<span className="signSubmitMore"><a href="javascript:void(0);" onClick={openLinkUrl.bind(this,linkurl,'2')}>{getLabel(17499,"更多")}</a></span>);
			btnsHtml = <div className="signSubmit">
				{btnsArr}
			</div>
		}

		return <div className="portal-element-workflow-signview">
				<Signature ref="Signature"/>
				<div id={`signPreview_${eid}`} className="signPreview" style={{height:showbtns ? '412px' : '372px'}}>
				<div className="arrowsblock"><img src="/images/ecology8/homepage/arrows_wev8.png"/></div>
				<div className="arrowsblockup"><img src="/images/ecology8/homepage/arrows_up_wev8.png"/></div>
				<div className="signContainer">
				<div className="signTitleContainer">
					<div className="signTitle">
						<a title={title} href='javascript:void(0);' onClick={openLinkUrl.bind(this,linkurl,'2')}>{title}</a>
					</div>
					<img className="signIconClose" src="/images/ecology8/homepage/close_wev8.png"/>
				</div>
				{ahtml}
				{/*<iframe height='450px' width="100%" border="0px" style={{border: '0px'}}></iframe>*/}
				{btnsHtml}
				<div className="params" style={{display:'none'}}>
					<input type="hidden" value="1" name="pageno"/>
					<input type="hidden" value="" name="requestid"/>
					<input type="hidden" value="" name="maxrequestlogid"/>
					<input type="hidden" value="" name="requestLogParams"/>
				</div>
				</div>
			</div>
		</div>
	}
}

class MyErrorHandler extends React.Component{
	render() {
		const hasErrorMsg = this.props.error && this.props.error !== "";
		return (
			<WeaErrorPage msg={hasErrorMsg?this.props.error:getLabel(385218,"对不起，该页面异常，请联系管理员！") } />
		);
	}
}
SignView = WeaTools.tryCatch(React, MyErrorHandler, { error: "" })(SignView);
export default SignView;

const SignContent = ({ item }) => {
	const {log_nodename ,operationname, displayname, displaydepid, displaydepname, displayid, img_path, receiveUser, log_operatedate, log_operatetime, log_remarkHtml } = item;
	var nameStr = '接收人 : ' + receiveUser;
	return <div className="wea-workflow-req-sign-list-content" >
          <div className="content-left">
        <img src={img_path} className="content-text-left-user-img"/>
        <div style={{width:'132px'}}>
          <p>
            <a href={`javascript:openhrm(${displayid})`} onClick={pointerXY.bind(this)}>{displayname}</a>
          </p>
          <span>
            <a href="/hrm/company/HrmDepartmentDsp.jsp?id=36" target="_blank" style={{color:'#9b9b9b',whiteSpace:'pre-wrap'}}>{displaydepname}</a>
          </span>
        </div>
      </div>
      <div className="content-right">
        <div className="content-right-remark-html"  dangerouslySetInnerHTML={{__html:log_remarkHtml}}>

        </div>
        <p style={{lineHeight:'24px',color:'#8a8a8a'}}>
          <span style={{overflow: 'hidden',textOverflow: 'ellipsis', whiteSpace:'nowrap',maxWidth:'295px', height: '20px', lineHeight: '20px',display:'block'}}>{nameStr}</span>
        </p>
        <p style={{lineHeight:'22px',marginTop:'10px',color:'#9a9a9a'}}>
          <span style={{marginRight:'8px'}}>{log_operatedate} {log_operatetime} </span>
          <span>[{log_nodename} / {operationname}]</span>
        </p>
      </div>
    </div>
}


